"""
Reference: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/jlil56u11
"""
import requests
import json
from datetime import datetime
from helper.common import logger

class Answers_Fetcher:
    def __init__(self, access_token, data_dir):
        self.__access_token = access_token
        self.__api_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions'
        self.__headers = {'Content-Type': 'application/json'}
        self.__data_dir = data_dir

    def __get_one_answer_from_wenxin(self, question):
        user_message = f"请你回答这个面试题：'{question}'。"
        payload = {
            "system": "你是一个计算机、编程领域的专家，你将回答关于“软件开发岗位”的面试题。"
                      "你的回答应该以纯文本的方式而不是Markdown的格式。"
                      "当你需要输出代码时，请先讲解思路，再给出C++代码。",
            "messages": [
                {"role": "user", "content": user_message}
            ]
        }
        full_url = f"{self.__api_url}?access_token={self.__access_token}"
        response = requests.post(full_url, json=payload, headers=self.__headers)
        result = response.json()

        logger.info(f"The request: {json.dumps(payload, indent=4, ensure_ascii=False)}.\n"
                    "The response:\n" + json.dumps(result, indent=4, ensure_ascii=False))
        return result

    def fetch_and_save_answers(self, questions):
        results = {}
        date_str = datetime.now().strftime("%Y-%m-%d")
        filename = f'{self.__data_dir}answers_{date_str}.json'
        
        for category, qs in questions.items():
            results[category] = {}
            for question in qs:
                answer_response = self.__get_one_answer_from_wenxin(question)
                if 'error_code' in answer_response:
                    logger.error("Error occurs when send request\n"
                                 f"Question: {question}.\n"
                                 f"ErrorMessage: {answer_response['error_msg'] if 'error_msg' in answer_response else 'No error message'}\n")
                    return None

                answer = answer_response['result'] if 'result' in answer_response else 'Error'
                results[category][question] = answer

                with open(filename, 'w') as file:
                    json.dump(results, file, indent=4, ensure_ascii=False)
                logger.info(f"File {filename} has been saved at {self.__data_dir}")
        return results
